package org.example.mq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.example.model.OrderMessage;
import org.example.service.ProductOrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
@RabbitListener(queues = "${mqconfig.order_close_queue}")
public class ProductOrderMQListener {

    @Autowired
    private ProductOrderService orderService;

    @RabbitHandler
    public void closeOrder(OrderMessage orderMessage, Message message, Channel channel) throws IOException {
        long tag = message.getMessageProperties().getDeliveryTag();
        boolean flag = orderService.closeOrder(orderMessage);
        try {
            if (flag) {
                log.info("支付成功，消费消息");
                channel.basicAck(tag, false);
            } else {
                log.info("支付失败，重回队列");
                channel.basicReject(tag, true);
            }
        } catch (IOException e) {
            log.error("定时关单失败，重回队列，orderMessage: {}, error: {}", orderMessage, e);
            channel.basicReject(tag, true);
        }
    }
}
